<?php

namespace App\Service\OpenShop\User;

use App\Enums\OpenShop\Feishu\CacheEnum;
use App\Enums\User\UserCacheEnum;
use App\Http\Middleware\OpenShop\UserPermissionAuth;
use App\Service\OpenShop\Feishu\BaseService;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Kuafu\IpWhite\Service\IpWhiteService;

class RmsUserService extends BaseService
{
    const GET_AUTH_USER_URL         = 'api/internal/user/getAuthInfo';
    const GET_AUTH_USER_INFO_URL    = 'api/internal/user/getAuthUserInfo';
    const GET_USER_INFO_URL         = 'api/internal/user/getUserInfoByIds';
    const GET_USER_INFO_BY_NAME_URL = 'api/internal/user/getWebUserList';
    const GET_PERMISSION_LIST_URL   = 'api/internal/sys/getAllPermission';
    const GET_SHOP_OWNER_COUNT      = 'api/internal/user/getShopOwnerCount';
    const GET_AREA_CODE_BY_AREA     = 'api/internal/getAreaCodeByArea';

    // 用户状态
    const USER_STATUS_NORMAL = 0; // 启用
    const USER_STATUS_BAN    = 1; // 禁用

    /**
     * 获取rms 用户基本信息
     * @param $userIds
     * @param array $headers
     * @return mixed
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function getRmsUserInfoByUserIds($userIds, $headers = [], bool $cache = false)
    {
        if (is_array($userIds)) {
            $userIds = implode(',', $userIds);
        }
        $cacheKey = UserCacheEnum::getRmsUsersInfoCache($userIds);
        if ($cache && Cache::has($cacheKey)) {
            return Cache::get($cacheKey);
        }

        $url    = config('rms.domain') . self::GET_USER_INFO_URL;
        $body   = [
            'userIds' => $userIds
        ];
        $header = getRmsReqHeader($headers);
        $data   = getRmsMessageCommon("GET", $url, $body, $header, 'query');

        if (count(explode(',', $userIds)) <= 50 && isset($data['code']) && $data['code'] == 200) {
            Cache::put($cacheKey, $data, 3600);
        }

        return $data;
    }

    public static function getAuthUserInfo($headers): ?array
    {
        $authorizations = $headers['authorization'] ?? [];
        if (is_string($authorizations)) {
            $authorization = $authorizations;
        } else {
            $authorization = $authorizations[0] ?? '';
        }
        if (!mb_strlen($authorization)) {
            return null;
        }

        $cacheKey = "openShop_rms_jwt_token_v2:" . md5($authorization);
        $expireTime = now()->addMinute();
        if (isTest()) {
            $expireTime = now()->addSeconds(5);
        }

        $data = Cache::remember($cacheKey, $expireTime, function () use ($headers) {
            $url      = config('rms.domain') . self::GET_AUTH_USER_URL;
            $header   = getRmsReqHeader($headers);
            $body     = '{}';
            $userInfo = getRmsMessageCommon("GET", $url, $body, $header, 'body');

            $code = $userInfo['code'] ?? null;

            if (200 === $code && ($userInfo['data']['id'] ?? 0) > 0) {
                return $userInfo;
            }

            if ($code == IpWhiteService::ERR_RESPONSE_CODE) {
                \App\Service\BaseService::throwErr($userInfo['msg'] ?? IpWhiteService::ERR_RESPONSE_MSG, $code);
            }

            \App\Service\BaseService::throwErr($userInfo['msg'] ?? 'token获取用户信息失败', $code);
        });

        return $data;
    }

    /**
     * 删除缓存 与  self getRmsAuthUserInfo() 方法对应
     *
     * @param $userId
     */
    public static function delRmsAuthUserInfoCache($userId)
    {
        $key      = 'openShop_rms_jwt_token:' . md5($userId);
        Redis::del($key);
    }

    public static function getRmsAuthUserInfo($userId, $shopId = null): ?array
    {
        $key      = 'openShop_rms_jwt_token:' . md5($userId);
        $userInfo = Redis::get($key);
        if (!empty($userInfo)) {
            Log::info("用户信息Redis 取", ['userId' => $userId]);
            return json_decode($userInfo, 1);
        }
        $url      = config('rms.domain') . self::GET_AUTH_USER_INFO_URL . '?userId=' . $userId;
        $header   = getRmsReqHeader([], $shopId);
        $body     = "{}";
        $userInfo = getRmsMessageCommon("GET", $url, $body, $header, 'body');
//        Log::info("用户信息 RMS 获取", [$userInfo]);
        if (200 === ($userInfo['code'] ?? null) && ($userInfo['data']['id'] ?? 0) > 0) {
            Redis::setex($key, getSwitchCacheTime(5), json_encode($userInfo));
            return $userInfo;
        }
        return null;
    }


    /**
     * 获取所有 openShop 的权限列表
     */
    public static function getAllPermission(string $module = UserPermissionAuth::MODULE_OPEN_SHOP)
    {
        $permission = getRmsUserInfoByAuth()->permissions ?? null;
        if ($permission !== null) {
            return $permission;
        }

        $key = 'rms_permission_list:'.$module;
        if (!$permission = Cache::get($key)) {
            $url    = config('rms.domain') . self::GET_PERMISSION_LIST_URL . '?platform=1&module='.$module;
            $header = getRmsReqHeader();
            $body   = "{}";
            $list   = getRmsMessageCommon("GET", $url, $body, $header, 'body');
            if (200 === ($list['code'] ?? null)) {
                if (!empty($list['data'])) {
                    $permission = $list['data'];
                } else {
                    $permission = [];
                }

                foreach ($permission as &$list) {
                    $list = ltrim($list, 'b.');
                }
                unset($list);

                $expireTime = now()->addMinutes(10);
                if (config('app.env') == 'qa') {
                    $expireTime = now()->subSeconds(2);
                }
                Cache::put($key, $permission, $expireTime);
            }
        }

        return $permission;
    }

    public static function getWebUserList($headers = [])
    {
        $url    = config('rms.domain') . self::GET_USER_INFO_BY_NAME_URL;
        $body   = [];
        $header = getRmsReqHeader($headers);
        $data   = getRmsMessageCommon("GET", $url, $body, $header, 'query');
        return $data['data'];
    }

    public static function getShopOwnerCount($headers = [])
    {
        $url    = config('rms.domain') . self::GET_SHOP_OWNER_COUNT;
        $body   = [];
        $header = getRmsReqHeader($headers);
        $data   = getRmsMessageCommon("GET", $url, $body, $header, 'query');
        return $data['data'] ?? '-';
    }

    public static function getAreaCodeByArea($area, $headers = [])
    {
        $url    = config('rms.domain') . self::GET_AREA_CODE_BY_AREA;
        $body   = [
            'area' => $area
        ];
        $header = getRmsReqHeader($headers);
        $data   = getRmsMessageCommon("GET", $url, $body, $header, 'query');
        return $data['data'] ?? [];
    }

    /**
     * 权限输出处理（多个权限转化成一个权限）
     * @param $controllerList
     * @param $permissionListAll
     * @return bool false-进行拦截  true-不拦截
     */
    public static function permissionOutUp($controllerList, $permissionListAll): bool
    {
        switch ($controllerList) {
            case 'cruise.cruise.supervisegrade':                 //任务处理-督导评分
            case 'cruise.cruise.supervisereject':                //任务处理-督导驳回
            case 'cruise.web.cruisecheckagainst.drawupagainst':  //任务处理-开具违约函
                $result = in_array('cruise.web.superviseoperate', $permissionListAll);
                break;
            default:
                $result = true;
        }
        return $result;
    }
}
